<?php

namespace app\admin\controller\order;

use app\common\controller\Backend;
use fast\Tree;
use Exception;
use think\Db;
use think\Log;

include_once APP_PATH . 'api/common.php';

/**
 *
 *
 * @icon fa fa-file
 */
class Order extends Backend
{

    /**
     * Order模型对象
     */
    protected $model = null;
    protected $noNeedRight = ["lists", "status"];
    protected $noNeedLogin = ["lists", "status"];


    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Order');
        $this->modelValidate = true;
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            // 获取城市和学校过滤参数
            $city_id = $this->request->get("city_id");
            $school_id = $this->request->get("school_id");

            // 调试日志
            error_log("Order Index - city_id: $city_id, school_id: $school_id");

            // 获取通用搜索参数
            $search = $this->request->get("search");

            $total = $this->model
                ->alias('order')
                ->join('fa_user student', 'order.user_id = student.id', 'LEFT')
                ->join('eb_classes classes', 'order.classes_id = classes.id', 'LEFT')
                ->join('fa_registration registration', 'order.user_id = registration.user_id and registration.table_id = order.table_id', 'LEFT')
                ->where("fa_user.id", "<>", 1)
                ->where(function($query){
                    $query->where("order.status", "=", 1)->whereOr("order.status", "=", 4);
                })
                ->where(function($query){
                    $query->where("order.pay_status", "=", 1)->whereOr("order.pay_status", "=", 4);
                });

            // 添加通用搜索条件（OR关系）
            if (!empty($search)) {
                $total = $total->where(function($query) use ($search) {
                    $query->whereOr("classes.name", "LIKE", "%{$search}%")
                          ->whereOr("order.user_id", "LIKE", "%{$search}%")
                          ->whereOr("student.nickname", "LIKE", "%{$search}%")
                          ->whereOr("registration.name", "LIKE", "%{$search}%")
                          ->whereOr("registration.phone", "LIKE", "%{$search}%");
                });
            }

            // 添加城市过滤
//            if (!empty($city_id)) {
//                $total = $total->where("order.city_id", "=", $city_id);
//            } else if (isset($_SESSION['think']['admin']['group_id']) && $_SESSION['think']['admin']['group_id'] == 2) {
//                $total = $total->where("order.city_id", "=", $_SESSION['think']['admin']['city_id']);
//            }

            // 添加学校过滤
            if (!empty($school_id)) {
                $total = $total->where("order.school_id", "=", $school_id);
            }

            $total = $total->where("order.status", "<>", -1);
            if ($_SESSION['think']['admin']['group_id'] == 3) {
                $total = $total->where("order.school_id", "=", $_SESSION['think']['admin']['school_id']);
            } elseif ($_SESSION['think']['admin']['group_id'] == 8) {
                $total = $total->where("order.community_id", "=", $_SESSION['think']['admin']['community_id']);
            }
            $total = $total->count();

            $list = $this->model
                ->alias('order')
                ->join('fa_user student', 'order.user_id = student.id', 'LEFT')
                ->join('eb_classes classes', 'order.classes_id = classes.id', 'LEFT')
                ->join('fa_registration registration', 'order.user_id = registration.user_id and registration.table_id = order.table_id', 'LEFT')
                ->field('order.*, student.mobile,student.nickname as student_name, classes.name as classes_name,registration.name as registration_name, registration.phone as registration_phone')
                ->where("fa_user.id", "<>", 1)
                ->where(function($query){
                    $query->where("order.status", "=", 1)->whereOr("order.status", "=", 4);
                })
                ->where(function($list){
                    $list->where("order.pay_status", "=", 1)->whereOr("order.pay_status", "=", 4);
                });

            // 添加通用搜索条件（OR关系）
            if (!empty($search)) {
                $list = $list->where(function($query) use ($search) {
                    $query->whereOr("classes.name", "LIKE", "%{$search}%")
                          ->whereOr("order.user_id", "LIKE", "%{$search}%")
                          ->whereOr("student.nickname", "LIKE", "%{$search}%")
                          ->whereOr("registration.name", "LIKE", "%{$search}%")
                          ->whereOr("registration.phone", "LIKE", "%{$search}%");
                });
            }


            // 添加学校过滤
            if (!empty($school_id)) {
                $list = $list->where("order.school_id", "=", $school_id);
            }

            //$list = $list->where("status", "=", 1);
            if ($_SESSION['think']['admin']['group_id'] == 3) {
                $list = $list->where("order.school_id", "=", $_SESSION['think']['admin']['school_id']);
            } elseif ($_SESSION['think']['admin']['group_id'] == 8) {
                $list = $list->where("order.community_id", "=", $_SESSION['think']['admin']['community_id']);
            }
            $list = $list->order('order.weigh desc,order.id desc')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            //$this->model->getLastSql();
            $list = collection($list)->toArray();
            foreach ($list as $key => $v) {
                $list[$key]['city_id'] = model("Cityarea")->getCity_idTextAttr($v['city_id'], $v);
                $list[$key]['school_id'] = model("School")->getSchool_idTextAttr($v['school_id'], $v);
                $list[$key]['pay_time'] = ($v['pay_time'] > 0) ? date("Y-m-d H:i:s", $v['pay_time']) : "";
            }

            for ($i = 0; $i < count($list); $i++) {
                $list[$i]['table_id'] = model("Coursetable")->getCoursetable_idTextAttr($list[$i]['table_id'], $list[$i]);
                $list[$i]['classes_id'] = model("Classes")->getClasses_idTextAttr($list[$i]['classes_id'], $list[$i]);
                $list[$i]['user_id'] = model("User")->getUser_idTextAttr($list[$i]['user_id'], $list[$i]);
                $list[$i]['payment_status'] = $this->model->getPayment_statusTextAttr($list[$i]['payment_status'], $list[$i]);
                $list[$i]['total_fee']=$list[$i]['total_fee']==""?$list[$i]['amount']:$list[$i]['total_fee'];
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
//        $this->assignconfig("relType",$_REQUEST['relType']);
//        $this->assignconfig("relId",$_REQUEST['relId']);
        $this->assignconfig("admin", $_SESSION['think']['admin']);
        return $this->view->fetch();
    }

    /**
     * 获取退款二维码
     */
    public function getRefundQrcode()
    {
        $id = $this->request->param('id');
        if (!$id) $this->error("ID不能为空");

        // 构造 scene 参数: refund,order_id
        $scene = "refund," . $id;
        $page = "pages/refund/refund"; // 小程序退款页面路径

        try {
            $mp = new \app\api\controller\MiniProgram;
            $config = \think\Config::get('wechat');

            if (empty($config) || empty($config['appid']) || empty($config['secret'])) {
                $this->error("微信配置缺失");
            }

            $appid = $config['appid'];
            $secret = $config['secret'];
            $accessToken = $mp->getAccessToken($appid, $secret);

            $client = new \GuzzleHttp\Client(['base_uri' => 'https://api.weixin.qq.com/', 'verify' => false]);
            $response = $client->post('wxa/getwxacodeunlimit', [
                'query' => ['access_token' => $accessToken],
                'json' => [
                    'page' => $page,
                    'scene' => $scene,
                    'check_path' => false,
                    'width' => 280,
                    'env_version' => 'release'
                ],
                'timeout' => 10
            ]);

            $body = (string)$response->getBody();
            if (getimagesizefromstring($body) === false) {
                $json = json_decode($body, true);
                $msg = isset($json['errmsg']) ? $json['errmsg'] : $body;
                $this->error("生成二维码失败: " . $msg);
            }

            $base64 = base64_encode($body);
            //$this->success("获取成功", $base64);
            echo json_encode(['code' => 1, 'msg' => '获取成功', 'data' => $base64]);
            exit;

        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 后端直接退款
     */
    public function refund()
    {
        $id = $this->request->param('id');
        if (!$id) $this->error("ID不能为空");

        $order = $this->model->alias('order')->join('fa_refund refund', 'order.id=refund.order_id and refund.status=1', 'LEFT')->field('order.*,refund.refund_id as refund_id_v,refund.refund_no,refund.status as refund_status')->where('order.id', $id)->find();
        if (!$order) $this->error("订单不存在");

        if ($order['pay_status'] != 1) {
            // 如果已有退款记录，尝试查询最新状态
            if (!empty($order['refund_id_v'])) {
                $this->getRefundStatus($order);
            }
            $this->error("订单未支付或已退款<br>退款单号：" . ($order['refund_id_v'] ?? '无'));
        }

        // 方案：手动构造退款请求
        try {
            $refund_no = 'REFUND' . date('YmdHis') . mt_rand(1000, 9999);
            $total_fee = $order['total_fee']; // 假设全额退款
            if($total_fee==null){
                $total_fee = $order['amount'];
            }
            $refund_fee = $order['amount'];

            // 创建退款记录
            $refundData = [
                'refund_no' => $refund_no,
                'order_id' => $order['id'],
                'user_id' => $order['user_id'],
                'total_fee' => $order['total_fee'],
                'refund_fee' => $refund_fee,
                'refund_reason' => '管理员后台退款',
                'status' => 0,
                'create_time' => time(),
                'update_time' => time()
            ];
            $refundId = \think\Db::name('refund')->insertGetId($refundData);

            // 调用微信退款
            $my = new \app\api\controller\v1\My;
            // 使用反射调用私有方法 processWechatRefund
            $method = new \ReflectionMethod(\app\api\controller\v1\My::class, 'processWechatRefund');
            $method->setAccessible(true);

            // 确保 pay_channel_order_sn 存在 (pay_channel_id)
            if (empty($order['pay_channel_order_sn']) && !empty($order['pay_channel_id'])) {
                $order['pay_channel_order_sn'] = $order['pay_channel_id'];
            }
            // 去除可能存在的空格
            $order['pay_channel_order_sn'] = trim($order['pay_channel_id']);
            error_log("Refund Transaction ID: '" . $order['pay_channel_order_sn'] . "'");

            $result = $method->invoke($my, $order['pay_channel_order_sn'], $refund_no, $total_fee, $refund_fee);
            if (isset($result['message']) && ($result['message'] == '订单已全额退款')) {
                $this->getRefundStatus($order);
                echo json_encode(['code' => 1, 'msg' => '退款成功', 'data' => ['refund_id' => $refundId]]);
                exit;
            }else if (isset($result['status']) && ($result['status'] == 'SUCCESS' || $result['status'] == 'PROCESSING')) {
                // 更新状态
                $order->save([
                    'status' => 4, // 已退款
                    'pay_status' => 4,
                    'refund_time' => strtotime($result['create_time']),
                    'refund_status' => 'SUCCESS',
                    'refund_id' => $refundId,
                    'refund_amount' => $refund_fee,
                    'refund_shop_no' => $refund_no,
                    'refund_no' => $result['refund_id'],
                ]);

                \think\Db::name('refund')->where('id', $refundId)->update([
                    'status' => 1,
                    'refund_id' => $result['refund_id'] ?? '',
                    'update_time' => time(),
                    'refund_status' => 'SUCCESS',
                    'user_received_account' => $result['user_received_account'] ?? '',
                    'out_refund_no' => $result['out_refund_no'] ?? '',
                    'order_out_refund_no' => $order['out_trade_no'] ?? '',
                    'out_trade_no' => $order['order_sn'] ?? '',
                    'order_out_trade_no' => $order['out_trade_no'] ?? '',
                    'refund_transaction_id' => $order['pay_channel_id'] ?? '',
                ]);
                echo json_encode(['code' => 1, 'msg' => '退款成功', 'data' => ['refund_id' => $refundId],['refresh' => true]]);
                exit;
            } else {
                $msg = isset($result['message']) ? $result['message'] : '退款失败';
                $this->error($msg);
            }

        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
    }

    function getRefundStatus($order)
    {
        // 微信退款查询API正确路径：/v3/refund/domestic/refunds/{out_refund_no}
        // 需要使用商户退款单号，而不是商户订单号
        if (empty($order['refund_no'])) {
            file_put_contents(ROOT_PATH . 'runtime/wechat_refund.log', "退款单号为空，无法查询\n", FILE_APPEND);
            return;
        }
        $order_id = $order['id'];
        $url = 'https://api.mch.weixin.qq.com/v3/refund/domestic/refunds/' . $order['refund_no'];

        // 加载微信支付配置
        $wechatConfig = config('wechatpay');
        $config = $wechatConfig['payment'] ?? [];

        if (empty($config)) {
            throw new \Exception('微信支付配置未找到');
        }

        // 发送查询请求
        $result = $this->requestWechatRefundQuery($url, $config);
        file_put_contents(ROOT_PATH . 'runtime/wechat_refund.log', json_encode($result, JSON_UNESCAPED_UNICODE) . "\n--查询结果\n", FILE_APPEND);
        // 处理返回结果
        if (isset($result) && !empty($result)&&isset($result['status'])&&$result['status']=='SUCCESS') {

            $refundInfo = [
                'refund_id' => $result['refund_id'] ?? '',
                'out_refund_no' => $result['out_refund_no'] ?? '',
                'out_trade_no' => $result['out_trade_no'] ?? '',
                'refund_status' => $result['status'] ?? 'UNKNOWN',
                'create_time' => $result['create_time'] ?? '',
                'success_time' => $result['success_time'] ?? '',
                'user_received_account' => $result['user_received_account'] ?? '',
            ];

            // 如果有退款金额信息
            if (isset($result['amount'])) {
                $refundInfo['total'] = $result['amount']['total'] / 100 ?? 0;
                $refundInfo['refund'] = $result['amount']['refund'] / 100 ?? 0;
                $refundInfo['payer_total'] = $result['amount']['payer_total'] / 100 ?? 0;
                $refundInfo['payer_refund'] = $result['amount']['payer_refund'] / 100 ?? 0;
            }

            if ($refundInfo['refund_status'] === 'SUCCESS') {
                $hasRefund = true;
                $refund = Db::name('refund')->where('order_id', $order_id)->find();
                Db::name('order')->where('id', $order_id)->update([
                    'status' => 4, // 已退款
                    'pay_status' => 4, // 已退款
                    'refund_id' => $refund['id'] ?? '',
                    'refund_time' => strtotime($refundInfo['success_time']),
                    'refund_status' => 'SUCCESS',
                    'refund_amount' => $refundInfo['payer_refund'] ?? $refundInfo['refund'],
                    'refund_no' => $refundInfo['refund_id'] ?? '',
                    'refund_shop_no' => $refundInfo['out_refund_no'] ?? '',
                    'pay_channel_order_sn' => $refundInfo['out_trade_no'] ?? '',
                ]);

                // 更新退款记录状态
                Db::name('refund')->where('id', $refund['id'])->update([
                    'status' => 1, // 退款成功
                    'refund_id' => $refundInfo['refund_id'] ?? '',
                    'update_time' => time(),
                    'refund_status' => 'SUCCESS',
                    'user_received_account' => $refundInfo['user_received_account'] ?? '',
                    'create_time' => strtotime($refundInfo['create_time'] ?? ''),
                    'refund_time' => date("Y-m-d H:i:s", strtotime($refundInfo['success_time'] ?? '')),
                    'order_out_refund_no' => $refundInfo['out_trade_no'] ?? '',
                    'out_refund_no' => $refundInfo['out_refund_no'] ?? '',
                    'out_trade_no' => $refundInfo['out_trade_no'] ?? '',
                ]);

                // 更新报名项目状态
                if (!empty($refund['order_id'])) {
                    Db::name('eb_apply_form_item')->where('order_id', $refund['order_id'])->update([
                        'pay_status' => 4, // 退款成功
                        'status' => 0, // 退款成功
                    ]);
                }
            }
            return $refundInfo;
        }else if($result['http_code']==404){
            $refund=model('refund')->where('order_id', $order_id)->find();
            $order=model('order')->where('id', $order_id)->find();
            if($order['refund_status']=='SUCCESS'){
                Db::name('order')->where('id', $order_id)->update([
                    'status' => 4, // 已退款
                    'pay_status' => 4, // 已退款
                ]);
            }
        }
    }


    private function requestWechatRefundQuery($url, $config)
    {
        // 直接使用 buildRefundAuth 方法生成认证头
        $auth = $this->buildRefundAuth('GET', $url, '', $config);

        // 发送请求
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: ' . $auth,
            'Accept: application/json',
            'User-Agent: FastAdmin/WeChatPay'
        ]);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_VERBOSE, true);

        // 记录请求信息
        file_put_contents(ROOT_PATH . 'runtime/wechat_refund.log',
            "\n=== 退款查询请求 ===\n" .
            "URL: " . $url . "\n" .
            "Auth: " . substr($auth, 0, 100) . "...\n" .
            "Time: " . date('Y-m-d H:i:s') . "\n",
            FILE_APPEND);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        $curlInfo = curl_getinfo($ch);

        // 记录响应信息
        file_put_contents(ROOT_PATH . 'runtime/wechat_refund.log',
            "HTTP Code: " . $httpCode . "\n" .
            "Response Length: " . strlen($response) . "\n" .
            "Response: " . $response . "\n" .
            "cURL Error: " . $error . "\n" .
            "Total Time: " . $curlInfo['total_time'] . "s\n" .
            "===================\n",
            FILE_APPEND);

        curl_close($ch);

        if ($httpCode >= 200 && $httpCode < 300) {
            $result = json_decode($response, true);
            return $result;
        } else {
            // 尝试解析错误响应
            $errorData = json_decode($response, true);
            $errorMessage = '微信退款查询失败，HTTP状态码: ' . $httpCode;

            if ($errorData && isset($errorData['message'])) {
                $errorMessage .= ', 错误信息: ' . $errorData['message'];
            }

            if ($errorData && isset($errorData['code'])) {
                $errorMessage .= ', 错误代码: ' . $errorData['code'];
            }

            if (!empty($error)) {
                $errorMessage .= ', cURL错误: ' . $error;
            }

            // 记录详细的调试信息
//            Log::error('微信退款查询失败', [
//                'url' => $url,
//                'http_code' => $httpCode,
//                'response' => $response,
//                'error' => $error
//            ]);
            return [
                'message' => $errorMessage,
                'url' => $url,
                'http_code' => $httpCode,
                'response' => $response,
                'error' => $error
            ];
            //throw new \Exception($errorMessage);
        }
    }


    private function buildRefundAuth($method, $url, $body, $config)
    {
        // 统一读取 wechat.pay 配置
        $fullConfig = config('wechatpay');

        $timestamp = time();
        $nonce = uniqid();
        $urlParts = parse_url($url);
        $canonicalUrl = ($urlParts['path'] ?? '/') . (isset($urlParts['query']) ? '?' . $urlParts['query'] : '');

        // 对于GET请求，body应该为空字符串而不是null
        if ($method === 'GET') {
            $body = '';
        }

        $message = $method . "\n" .
            $canonicalUrl . "\n" .
            $timestamp . "\n" .
            $nonce . "\n" .
            $body . "\n";

        // 获取私钥路径，支持多种配置名称，并修正路径
        $keyPath = $fullConfig['merchant_private_key_path'] ?? $fullConfig['key_path'] ?? null;
        if (empty($keyPath)) {
            throw new \Exception('微信支付配置中缺少私钥路径配置');
        }

        // 检查私钥文件是否存在
        if (!file_exists($keyPath)) {
            throw new \Exception('微信支付私钥文件不存在: ' . $keyPath);
        }

        $signature = $this->generateRefundSign($message, $keyPath);

        // 获取商户ID，支持多种配置名称
        $merchantId = $fullConfig['merchant_id'] ?? $fullConfig['mchid'] ?? '';
        if (empty($merchantId)) {
            throw new \Exception('微信支付配置中缺少商户ID');
        }

        // 获取商户证书序列号，支持多种配置名称
        $mchSerialNo = $fullConfig['merchant_serial_no'] ?? $fullConfig['serial_no'] ?? $fullConfig['mch_serial_no'] ?? '5C5D72F82C6A51FCC19C64E0C53661EAF59D7881';

        return sprintf(
            'WECHATPAY2-SHA256-RSA2048 mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"',
            $merchantId,
            $nonce,
            $timestamp,
            $mchSerialNo,
            $signature
        );
    }

    /**
     * 生成退款请求签名
     *
     * @param string $message 签名串
     * @param string $keyPath 商户API私钥路径
     * @return string 签名
     */
    private function generateRefundSign($message, $keyPath)
    {

        // 检查私钥文件是否存在
        if (!file_exists($keyPath)) {
            throw new \Exception('微信支付私钥文件不存在: ' . $keyPath);
        }

        $privateKey = openssl_pkey_get_private(file_get_contents($keyPath));
        if (!$privateKey) {
            throw new \Exception('无法加载商户API私钥');
        }

        $signature = '';
        if (!openssl_sign($message, $signature, $privateKey, OPENSSL_ALGO_SHA256)) {
            throw new \Exception('签名生成失败: ' . openssl_error_string());
        }

        return base64_encode($signature);
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }

                // 自动插入session中的城市和学校ID
                if (isset($_SESSION['think']['admin']['city_id']) && !empty($_SESSION['think']['admin']['city_id'])) {
                    $params['city_id'] = $_SESSION['think']['admin']['city_id'];
                }
                if (isset($_SESSION['think']['admin']['school_id']) && !empty($_SESSION['think']['admin']['school_id'])) {
                    $params['school_id'] = $_SESSION['think']['admin']['school_id'];
                }

                // 调试日志
                error_log("Order Add - Auto inserted city_id: " . ($params['city_id'] ?? 'null') . ", school_id: " . ($params['school_id'] ?? 'null'));

                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        //$this->model->validate($validate);
                    }
                    // 使用时间戳格式，与模型中的 autoWriteTimestamp = 'int' 设置一致
                    $params['create_time'] = time();
                    unset($params['delete_time']);
                    unset($params['update_time']);
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assignconfig("admin", $_SESSION['think']['admin']);
        $create_time = time();
        $this->view->assign("create_time", $create_time);
        $update_time = time();
        $this->view->assign("update_time", $update_time);
        $delete_time = time();
        $this->view->assign("delete_time", $delete_time);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                // 自动插入session中的城市和学校ID（如果当前记录没有设置的话）
                if (isset($_SESSION['think']['admin']['city_id']) && !empty($_SESSION['think']['admin']['city_id'])) {
                    if (empty($row['city_id'])) {
                        $params['city_id'] = $_SESSION['think']['admin']['city_id'];
                    }
                }
                if (isset($_SESSION['think']['admin']['school_id']) && !empty($_SESSION['think']['admin']['school_id'])) {
                    if (empty($row['school_id'])) {
                        $params['school_id'] = $_SESSION['think']['admin']['school_id'];
                    }
                }

                // 调试日志
                error_log("Order Edit - Auto inserted city_id: " . ($params['city_id'] ?? 'null') . ", school_id: " . ($params['school_id'] ?? 'null'));

                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        //$row->validate($validate);
                    }
                    // 使用时间戳格式，与模型中的 autoWriteTimestamp = 'int' 设置一致
                    $params['update_time'] = time();
                    unset($params['delete_time']);
                    unset($params['create_time']);
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assignconfig("admin", $_SESSION['think']['admin']);
        //$row=json_decode(json_encode($row),true);
        $this->view->assign("row", $row);
        return $this->view->fetch();

    }

    /**
     * 添加
     */
    public function view($ids = NULL)
    {
        $row = $this->model->getRow($ids);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function lists($ids = NULL)
    {
        $where = "where 1=1";
        if ($_SESSION['think']['admin']['group_id'] != 1) {
            $where .= " and city_id='{$_SESSION['think']['admin']['city_id']}'";
        }
        $page = 1;
        $pagesize = 50;
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                $keyField = $this->request->request("keyField");
                $keyValue = $this->request->request("keyValue");
                $page = $this->request->request("pageNumber");
                $page = ($page == null) ? 1 : $page;
                $pagesize = $this->request->request("pageSize");
                $pagesize = ($pagesize == null) ? 10 : $pagesize;
                if ($keyValue != "") {
                    $nn = preg_split("/\,/", $keyValue);
                    for ($i = 0; $i < count($nn); $i++) {
                        $where .= " and $keyField='{$nn[$i]}'";
                    }
                }
            } else {
                $where = "where 1=1";
                if (isset($_REQUEST['city_id']) && $_REQUEST['city_id'] > 0) {
                    //$where.=" and city_id=".$_REQUEST['city_id'];
                }
            }
        }
        $sql = "select user_id,__firstfield__ name from dev002_gxyusheng.fa_order $where limit " . (($page - 1) * $pagesize) . ",$pagesize";
        $list = db()->query($sql);

        $total = db()->query("select count(1) as c from  dev002_gxyusheng.fa_order $where")[0];
        echo json_encode(array("list" => $list, "total" => $total['c']));
        exit;
    }

    public function status($ids = '')
    {
        $ids = $this->request->post('ids');
        if (empty($ids)) {
            $this->error('没有选中!');
        }
        try {
            $result = $this->model->where("id", "=", $ids)->field("status")->find();
            $v = $result->status == 1 ? 0 : 1;
            $this->model->where("id", "=", $ids)->update(["status" => $v]);
            $this->success('切换成功!');
        } catch (Exception $e) {
            $this->error('切换失败!' . $e->getMessage());
        }
    }

    public function changeStatus($ids = '')
    {
        $ids = $this->request->post('ids');
        if (empty($ids)) {
            $this->error('没有选中!');
        }
        try {
            $result = $this->model->where("id", "=", $ids)->field("status")->find();
            $v = $result->status == 1 ? 0 : 1;
            $this->model->where("id", "=", $ids)->update(["status" => $v]);
            $this->success('切换成功!');
        } catch (Exception $e) {
            $this->error('切换失败!' . $e->getMessage());
        }
    }

    public function del($ids = NULL)
    {

    }

    public function pay()
    {
        $ids = $this->request->post('ids');
        if (empty($ids)) {
            $this->error('没有选中!');
        }
        try {
            $result = $this->model->where("id", "=", $ids)->field("payment_status")->find();
            $v = $result->payment_status == 1 ? 0 : 1;
            $this->model->where("id", "=", $ids)->update(["payment_status" => $v]);
            $this->success('切换成功!');
        } catch (Exception $e) {
            $this->error('切换失败!' . $e->getMessage());
        }
    }

}
